﻿/*
 *Author: Jeff Liu 
 *
 *Under MIT License
 *jebberwocky@gmail.com
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CtpGglPlaces.Interface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CtpGglPlaces.Impl
{
    public class JsonPlaceDetailsParser : IPlaceDetailsParser
    {
        public PlaceDetailsResult Parse(string json)
        {
            PlaceDetailsResult pdresult = new PlaceDetailsResult();

            JObject o = JObject.Parse(json);
            pdresult.Status = (String)o["status"];
            PlaceDetailsObj pobj = new PlaceDetailsObj();
            JObject ojb = (JObject)o["result"];
            pobj.Name = (String)ojb["name"];
            JArray types = (JArray)ojb["types"];
            List<String> stypes = new List<String>();
            for (int i = 0; i < types.Count; i++)
                stypes.Add((String)types[i]);
            pobj.Types = stypes;
            pobj.Vicinity = (String)ojb["vicinity"];
            pobj.FormattedAddress = (String)ojb["formatted_address"];
            pobj.FormattedPhoneNumber = (String)ojb["formatted_phone_number"];
            JObject geo = (JObject)ojb["geometry"];
            JObject geo_location = (JObject)geo["location"];
            pobj.Geometry.Location = new GeoPointImpl(
                DataUtil.StringToDouble(geo_location["lng"].ToString()),
                DataUtil.StringToDouble(geo_location["lat"].ToString())
                );
            pobj.Rating = (ojb["rating"]== null)? 0.0:(double)ojb["rating"];
            pobj.Url = (String)ojb["url"];
            pobj.Icon = (String)ojb["icon"];
            pobj.Reference = (String)ojb["reference"];
            pobj.Id = (String)ojb["id"];
     
            JArray addComps = (JArray)ojb["address_components"];
            pobj.AddressComponents = new List<AddressComponent>();
            for (int i = 0; i < addComps.Count; i++)
            {
                AddressComponent acomp = new AddressComponent();
                acomp.Types = new List<String>();
                JObject jo = (JObject)addComps[i];
                acomp.LongName = (String)jo["long_name"];
                acomp.ShortName = (String)jo["short_name"];
                JArray _types = (JArray)jo["types"];
                for (int j = 0; j < _types.Count; j++)
                {
                    acomp.Types.Add((String)_types[j]);
                }
                pobj.AddressComponents.Add(acomp);
            }
            pdresult.Result = pobj;
 
            JArray htmls = (JArray)o["html_attributions"];
            pdresult.HtmlAttributions = new List<string>();
            for (int i = 0; i < htmls.Count; i++)
                pdresult.HtmlAttributions.Add((String)htmls[i]);
            return pdresult;
        }
    }
}
